import Vue from 'vue'
import Vuex from 'vuex'
import Antd from 'ant-design-vue'
// import From from 'ant-design-vue'
import router from './router'
import 'ant-design-vue/dist/antd.css'
// import G2 from '@antv/g2'
import VueI18n from 'vue-i18n'
import store from './store/index'
import axios from 'axios';
import { langzh } from './language/zh'
import { langen } from './language/en'
import VueDraggableResizable from 'vue-draggable-resizable'
import * as echarts from 'echarts';
import request from './request/request'
import App from './App.vue'
import config from './request/configEnv/index'
import api from './api/index'
import Iconfont from '@/assets/iconfont/icon'
// import { detectZoom } from "./untils/detectZoom";

import './assets/iconfont/iconfont.css'
import './assets/css/index.scss'

// const m = detectZoom();
// document.body.style.zoom = 100 / Number(m);

Vue.component('vue-draggable-resizable', VueDraggableResizable)
Vue.component("Iconfont", Iconfont);
import Directives from '@/untils/directives'
Vue.use(Directives)

// import Base64 from 'js-base64'
// Vue.use(Base64)


// 解决 passive警告
// import 'default-passive-events'
// import '../static/fonts/iconfont.css'
// import echarts from 'echarts'
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
Vue.prototype.$axios = axios;
Vue.prototype.$api = api;
Vue.prototype.$echarts = echarts;
Vue.prototype.$portStr = `:${window.location.port}/` ;
Vue.prototype.$protocolStr = window.location.protocol + '//';
// Vue.prototype.$portStr = ':8000/';
// Vue.prototype.$protocolStr = 'http://';

// 动态指定
Vue.prototype.allurl = config.api.allurl;
Vue.prototype.wsurl = config.api.wsurl;

// Vue.prototype.allurl='http://192.168.5.81:8000/'
// Vue.prototype.wsurl='192.168.5.153:8000'
// Vue.prototype.allurl=window.location.protocol+'//'+window.location.hostname+':8000/'
// Vue.prototype.wsurl=window.location.hostname+':8000'

//远程映射
// Vue.prototype.allurl='http://14.18.153.83:8000/'
// Vue.prototype.wsurl='14.18.153.83:8000'
// Vue.prototype.installurl=window.location.protocol+'//'+window.location.hostname+':8888/'
// Vue.prototype.installurl = 'http://192.168.100.199:3000/'

Vue.prototype.namePattern = /^[a-zA-Z][a-zA-Z0-9_:-]{2,31}$/; //全局名字的正则
Vue.config.productionTip = false
Vue.use(Antd)
// Vue.use(From)
Vue.use(Vuex)
Vue.use(VueI18n)
const i18n = new VueI18n({
  // locale: 'zh',
  messages: {
    'zh': langzh, // 简体中文
    'en': langen, // 英文
  }
})

//节流函数（防止同一页面多次弹出500的错误信息）
let startTime = 0;
function throttle(fn, wait){
  return function(){
    let endTime = Date.now();
    if(endTime - startTime > wait){
      fn();
      startTime = endTime;
    }
  }
}
function error500() {
  if(i18n.locale=='zh'){
    Vue.prototype.$message.error('后台响应失败，请联系管理员!');
  }else{
    Vue.prototype.$message.error('The server response failed, please contact the administrator!');
  }
}
function errorElse() {
  if(i18n.locale=='zh'){
    Vue.prototype.$message.error('未知错误，请联系管理员!');
  }else{
    Vue.prototype.$message.error('Unknown error, please contact the administrator!');
  }
}
// axios响应错误处理
// axios.defaults.timeout = 1000 * 60; // 超时时间
axios.interceptors.response.use(
  response => {
    let flag = false
    if (response.data.params) {
      if (response.data.params.detail) flag = response.data.params.detail.indexOf('timeout') !=-1
      else flag = false
    } else {
      flag = false
    }
    // (response.data.params?(response.data.params.detail?response.data.params.detail.indexOf('timeout') !=-1:false):false)
    if(response.data.flag == 1 && flag) {
      if(i18n.locale=='zh'){
        Vue.prototype.$message.error('后台响应超时，请刷新重试!');
      }else{
        Vue.prototype.$message.error('The server response timeout, please refresh and try again!');
      }
    }
  // 对响应数据做点什么
  return response;
}, error => {
  // 对响应错误做点什么
  // 错误码500，提示错误信息
  if (error.response.status == 500) {
    throttle(error500, 1500)();
  }
  // 错误码401，提示错误信息
  else if (error.response.status == 401) {
    if(i18n.locale=='zh'){
      Vue.prototype.$message.error('登录超时，请重新登录!');
    }else{
      Vue.prototype.$message.error('Login timeout, please log in again!');
    }
    router.push('/login');
  }
  // 超时处理
  else if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1) {
    if(i18n.locale=='zh'){
      Vue.prototype.$message.error('请求超时，请稍后再试！');
    }else{
      Vue.prototype.$message.error('Request timeout, please try again later!');
    }
  }
  // 其他错误，提示错误信息
  else {
    throttle(errorElse, 1500)();
  }
  return Promise.reject(error);
});
// 关闭上一页面未完成的请求
axios.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(function(cancel) {
      store.commit('pushToken', { cancelToken: cancel });
    });
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
router.beforeEach((to, from, next) => {
  // 判断系统语言 如果没有设置，则默认为中文
  if (localStorage.getItem("language") == null) {
    i18n.locale = 'zh';
  } else {
    i18n.locale = JSON.parse(localStorage.getItem("language"));
  }
  // 取消上一页面的请求
  store.commit('clearToken'); // 取消请求
  //返回到登录界面，清空所有session
  if (to.name == 'Login') {
    localStorage.removeItem('islogin')
    localStorage.removeItem('loginuser')
    localStorage.removeItem('user_id')
    localStorage.removeItem('routes');
    localStorage.removeItem('tags');
    localStorage.removeItem('authToken');
    // localStorage.clear();
  }
  //如果输入的路由地址不存在，
  if (to.name == null) {
    // 中断当前的导航，重置到 from 路由对应的地址
    next(false);
  } else if (to.meta.requiresAuth) {
    //需要登录权限进入的路由
    // if (JSON.parse(localStorage.getItem('islogin')) == true) {
    //   //取得到登录信息，进行下一步
    //   next();
    // } else {
    //   //取不到登录信息
    //   next({ path: '/' });
    // }
    //给超融合用的
    //需要登录权限进入的路由
    if (JSON.parse(localStorage.getItem('islogin'))) {
      //取得到登录信息，进行下一步

      //判断角色权限能否直接通过导航栏进
      let routePath = JSON.parse(localStorage.getItem('routes'));
      routePath.push('/block/detail');
      if(routePath.indexOf(to.path) != -1) {
        next();
      }else {
        next('/');
      }
      next();
    } else {
      //取不到登录信息(判断是否从外部登录)
      let fromUrl = window.location.href;
      let name_start_index = fromUrl.indexOf('=');
      let name_end_index = fromUrl.indexOf('&');
      let token_start_index = name_end_index + 6;
      let out_login_name = '';//从外部应用登录的登录名
      let token = '';
      if(name_start_index!=-1 && name_end_index !=-1) {
        out_login_name = fromUrl.slice(name_start_index+1, name_end_index);
      }
      token = fromUrl.slice(token_start_index+1);
      if(out_login_name && token) {
        next()
      }else {
        next('/')
      }
    }
  } else {
    //不需要登录权限
    next();
  }
});
// router.beforeEach((to, from, next) => {  //路由守卫
//   if (to.matched.some(record => record.meta.requiresAuth)) {
//     let res = localStorage.getItem('islogin')
//     if (res && res == true) {
//       next()
//     }
//     else {
//       if (from.name == 'Login' && res == null) {
//         next({ path: '/' })
//       }
//       else {
//         next()
//       }
//     }
//     if (to.name == 'Login') {
//       localStorage.clear() //返回到登录界面，清空所有session
//       next()
//     }
//   }
//   else {
//     next();
//   }
// })
new Vue({
  router,
  store,
  i18n,
  render: h => h(App),

  mounted() {
    String.prototype.format = function (opts) {//use 'my name is ${name}'.format({name:'lake'})
      let data = Array.prototype.slice.call(arguments, 0),
        toString = Object.prototype.toString;
      if (data.length) {
        data = data.length == 1 ?
          (opts !== null && (/\[object Array\]|\[object Object\]/.test(toString.call(opts))) ? opts : data) : data;
        return this.replace(/\$\{(.+?)\}/g, function (match, key) {
          let replacer = data[key];
          // chrome 下 typeof /a/ == 'function'
          if ('[object Function]' == toString.call(replacer)) {
            replacer = replacer(key);
          }
          return ('undefined' == typeof replacer ? '' : replacer);
        });
      }
      return this;
    }
    Vue.prototype.asFormat = function (str, params) {//asFormat是函数名
      // console.log('params', params)
      let start = 0;
      let end = 0;
      let str2 = str
      let srr = ''
      let obj = {}
      for (const item of str2) {
        start = str2.indexOf('{') + 1
        end = str2.indexOf('}')
        srr = str2.slice(start, end)
        for (let k in params) {
          if (srr == k) {
            obj[srr] = params[k]
          }
        }
        str2 = str2.substring(end + 1)
        if (start < 1) break;
      }
      str = str.format(obj)
      return str;
    }

    Vue.prototype.model = function (ids) {
      let themodel = ''
      let _res = JSON.parse(localStorage.getItem('basetips'))
      if (this.$store.state.language != null) {
        // this.language = localStorage.getItem('language')
        try {
          if (this.$store.state.language == 'zh') {
            themodel = _res[ids].zh_CN
          }
          else {
            themodel = _res[ids].en_US
          }
          localStorage.setItem('themodel', themodel)
        } catch{
          if (this.$store.state.language == 'zh') {
            themodel = '未知提示'
          }
          else {
            themodel = 'Unknown prompt'
          }
          localStorage.setItem('themodel', themodel)
        }
      }
      return themodel
    }

    Vue.prototype.notice = function (ids, params, flag) {  //消息通知
      let _this = this
      _this.$store.state.tipslist.unshift({ ids: ids, des: _this.asFormat(localStorage.getItem('themodel'), params), ds: params, status: flag, time: (new Date()).toLocaleString(), extend: false })
      _this.$store.commit('gettips', {
        tipslist: _this.$store.state.tipslist
      })
      _this.$notification.open({ message: _this.$t("Operation-prompt"), description: _this.asFormat(localStorage.getItem('themodel'), params) }); //提示信息弹窗显示
      // localStorage.setItem('themodel', themodel)
    }

    Vue.prototype.gettask = function () {
      let count = 0
      request('get', this.allurl + 'status/task').then(res => {
      // this.$axios.get(this.allurl + 'status/task').then(res => {
        for (const item of res.data) {
          if(item.flag == 2){
            count++;
          }
          this.model(item.id) //返回模板
          item.des = this.asFormat(localStorage.getItem('themodel'), item.params)
          item.extend = false //控制是否展开
        }
        if(count !== 0){
          this.$store.commit('gettaskflag', {
            taskflag: true,
          })
        }else{
          this.$store.commit('gettaskflag', {
            taskflag: false,
          })
        }
        this.$store.commit('gettasks', {
          tasklist: res.data,
        })
        localStorage.removeItem('themodel')  //清除缓存的参数，防止后续出错
      })
    }
  //通知交互: 全局监听
    Vue.prototype.resetSetItem = function (key, newVal) {
      if (key === 'watchStorage') {
          // 创建一个StorageEvent事件
          let newStorageEvent = document.createEvent('StorageEvent');
          const storage = {
              setItem: function (k, val) {
                  localStorage.setItem(k, val);
                  // 初始化创建的事件
                  // newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
                  newStorageEvent.StorageEvent('setItem', false, false, k, null, val, null, null);
                  // 派发对象
                  window.dispatchEvent(newStorageEvent)
              }
          }
          return storage.setItem(key, newVal);
      }
   }
   //通知交互：封装监听变化 刷新
   Vue.prototype.addListener = function (model) {
      window.addEventListener('setItem', ()=> { 
        this.newVal = JSON.parse(localStorage.getItem('watchStorage'));
        if(this.newVal.module == model){
            this.model(this.newVal.id) //返回模板
            this.notice(this.newVal.id, this.newVal.params, this.newVal.flag) //通知列表显示
        }
    })
  }
   Vue.prototype.addListenerfun = function (model, fn) {
      window.addEventListener('setItem', ()=> { 
        this.newVal = JSON.parse(localStorage.getItem('watchStorage'));
        if(this.newVal.module == model){ 
          //是函数，调用函数刷新数据
            fn()
            // console.log(this.newVal.module,'哈哈哈哈')
        }
    })
  }

    // this.gettask()//定时刷新页面数据
    Vue.prototype.bytesToBs = (limit) => {            //单位的转换
      let size = "";
      if (limit < 1 * 1000) { //如果小于0.1k转化成B
        size = limit.toFixed(1) + " ";
      } else if (limit < 1 * 1000 * 1000) {//如果小于0.1M转化成K
        size = (limit / 1000).toFixed(1) + " K";
      } else if (limit < 1 * 1000 * 1000 * 1000) { //如果小于0.1G转化成M
        size = (limit / (1000 * 1000)).toFixed(1) + " M";
      } else if (limit < 1 * 1000 * 1000 * 1000 * 1000) { //如果小于0.1T转化成G
        size = (limit / (1000 * 1000 * 1000)).toFixed(1) + " G";
      } else { //其他转化成TiB
        size = (limit / (1000 * 1000 * 1000 * 1000)).toFixed(1) + " T";
      }
      let sizestr = size + "";
      let len = sizestr.indexOf("\.");
      let dec = sizestr.slice(len + 1, 2);
      if (dec == "00") {//当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.slice(len + 3, 2);
      }
      return sizestr;
    }

    Vue.prototype.bytesToSize = (limit) => { //单位的转换
      let size = "";
      if (limit < 1 * 1024) { //如果小于0.1KiB转化成B
        size = limit.toFixed(1) + " B";
      } else if (limit < 1 * 1024 * 1024) {//如果小于0.1MiB转化成KiB
        size = (limit / 1024).toFixed(1) + " KiB";
      } else if (limit < 1 * 1024 * 1024 * 1024) { //如果小于0.1GiB转化成MiB
        size = (limit / (1024 * 1024)).toFixed(1) + " MiB";
      } else if (limit < 1 * 1024 * 1024 * 1024 * 1024) { //如果小于0.1TiB转化成GiB
        size = (limit / (1024 * 1024 * 1024)).toFixed(1) + " GiB";
      } else { //其他转化成TiB
        size = (limit / (1024 * 1024 * 1024 * 1024)).toFixed(1) + " TiB";
      }
      let sizestr = size + "";
      let len = sizestr.indexOf("\.");
      let dec = sizestr.slice(len + 1, 2);
      if (dec == "00") {//当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.slice(len + 3, 2);
      }
      return sizestr;
    }
    Vue.prototype.bytesToSize2 = (limit) => { //单位的转换
      let size = "";
      if (limit < 1 * 1000) { //如果小于0.1K转化成
        size = limit.toFixed(1);
      } else if (limit < 1 * 1000 * 1000) {//如果小于0.1MB转化成K
        size = (limit / 1000).toFixed(1) + " K";
      } else if (limit < 1 * 1000 * 1000 * 1000) { //如果小于0.1GB转化成M
        size = (limit / (1000 * 1000)).toFixed(1) + " M";
      } else if (limit < 1 * 1000 * 1000 * 1000 * 1000) { //如果小于0.1TB转化成G
        size = (limit / (1000 * 1000 * 1000)).toFixed(1) + " G";
      } else { //其他转化成T
        size = (limit / (1000 * 1000 * 1000 * 1000)).toFixed(1) + " T";
      }
      let sizestr = size + "";
      let len = sizestr.indexOf("\.");
      let dec = sizestr.slice(len + 1, 2);
      if (dec == "00") {//当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.slice(len + 3, 2);
      }
      return sizestr;
    }

  }

}).$mount('#app')
